<?php
/**
 * 权限规则类
 * Created by PhpStorm.
 * User: zhangbing
 * Date: 2018/7/20
 * Time: 15:45
 */
namespace app\admin\controller;

class Rule extends Base{
    /**
     * 权限列表
     * search 参数 $this->params:表单参数 input精确查找 时间查找 select状态查找
     * @return \think\response\View
     */
    public function ruleList(){
        $search = search($this->params,['rule_name']);
        $where  = $search['where'] ?: '';
        $list   = $this->getList($this->auth_rule, $where);
        if(!$this->params) $list = infinite($list);  // 检索的话不递归

        foreach ($list as $k=>$v) {
            $list[$k]['topid'] = 0;
            if ($v['pid'] != 0) {
                $list[$k]['topid'] = infiniteTop($list, $v['pid']);
            }
        }
        $count = count($list);
        return view('ruleList',['list'=>$list,'count'=>$count,'params'=>$search['params']]);
    }

    /**
     * 权限规则
     * @return array|\think\response\View
     */
    public function ruleSave(){
        $info = !empty($this->params['id']) ? $this->getRow($this->auth_rule, $this->params['id']) : [
            'rule_name' => '',
            'auth_rule' => '',
            'pid'       => '',
            'icon'      => '',
            'sort'      => '',
            'status'    => \Param::STATUS_ON,
            'id'        => ''
        ];

        if(IS_POST){
            try{
                if (!empty($this->params['id'])) {
                    //todo 更新
                    $validate = self::validate($this->params,'Rule.ruleSave');  // 场景验证
                    if(true !== $validate) throw new \Exception($validate, -1);

                    $result = compare($this->params,$info);  //参数对比, 拼接变动的参数，无改动直接返回
                    if(!$result) return success();

                    $num = $this->getCount($this->auth_rule, ['pid'=>$info['id']]);  // 判断权限是否有子权限
                    if($info['pid'] == 0 && !empty($this->params['pid']) && $num > 0) throw new \Exception('该顶级权限下有子权限', -1);

                    $this->params['auth_rule'] = strtolower($this->params['auth_rule']);
                    $row = $this->auth_rule->update($this->params);  // 修改权限
                    if(false === $row) throw new \Exception('操作失败', -1);

                    $this->logs[] = ['修改权限', \Param::LOG_TYPE_EDIT, "修改“ID：{$info['id']}”权限{$result}"];
                } else {
                    //todo 添加
                    $validate = self::validate($this->params, 'Rule.ruleAdd');  // 场景验证
                    if(true !== $validate) throw new \Exception($validate, -1);

                    $this->params['auth_rule'] = strtolower($this->params['auth_rule']);
                    $id = $this->auth_rule->insertGetId($this->params);  // 添加权限
                    if(!$id) throw new \Exception('操作失败', -1);

                    $this->logs[] = ['新增权限', \Param::LOG_TYPE_ADD, "新增“ID：{$id}”权限“{$this->params['rule_name']}”"];
                }
            } catch(\Exception $e) {
                return error($e->getCode(),$e->getMessage());
            }
            logs($this->logs);  // 添加操作日志
            return success();
        }
        $list = $this->getList($this->auth_rule, ['status'=>\Param::STATUS_ON]);  //获取权限列表
        $list = infinite($list);

        return view('ruleSave', ['list'=>$list, 'info'=>$info]);
    }

    /**
     * 修改状态
     * @return array
     */
    public function status(){
        if(IS_POST){
            try{
                $info = $this->getRow($this->auth_rule, $this->params['id']);
                if(!$info || $info['status'] == \Param::STATUS_DEL) throw new \Exception('该权限不存在', -1);

                $row = $this->auth_rule->update(['id'=>$this->params['id'],'status'=>$this->params['status']]);
                if (false === $row) throw new \Exception('操作失败', -1);

                $status = $this->params['status'] == \Param::STATUS_ON ? '已启用' : '已禁用';

                $this->logs[] = ['修改权限', \Param::LOG_TYPE_EDIT, "修改“ID：{$info['id']}”权限“{$info['rule_name']}”状态为“{$status}”"];
            } catch(\Exception $e) {
                return error($e->getCode(),$e->getMessage());
            }
            logs($this->logs);  // 添加操作日志
            return success();
        }
    }
}